package top.mask.zk.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * ClassName DistributeServer
 * Create by hx
 * Date 2021/7/16 1:44 下午
 */

public class DistributeServer {
    private String connectString = "127.0.0.1:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zk;

    public static void main(String[] args) throws InterruptedException, KeeperException {
        DistributeServer server = new DistributeServer();

        //1. 获取zk连接
        server.getConnect();

        //2. 注册服务器到zk集群
        server.regist();

        //3. 启动业务逻辑
        server.business();

    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist() throws InterruptedException, KeeperException {
        String create = zk.create("/servers", "hostname".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("hostname" + "is online");
    }

    private void getConnect() {
        try {
            zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
               @Override
               public void process(WatchedEvent watchedEvent) {

               }
           });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
